package edu.ncst.baseweb.service.impl.web;

import cn.wintersun.basecommon.common.Result;
import edu.ncst.baseweb.dao.web.LabPlatform;
import edu.ncst.baseweb.mapper.LabPlatformMapper;
import edu.ncst.baseweb.service.intrer.web.LabPlatformService;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Base64;
import java.util.List;

@Service
public class LabPlatformServiceImpl implements LabPlatformService {

    @Autowired
    private LabPlatformMapper labPlatformMapper;

    private String readImageAsBase64(String imagePath) throws IOException {
        Path path = Paths.get(imagePath);
        byte[] imageData = Files.readAllBytes(path);
        return Base64.getEncoder().encodeToString(imageData);
    }

    public Result<List<LabPlatform>> list(){
        List<LabPlatform> labPlatformList = labPlatformMapper.selectList(null);
        for (LabPlatform labPlatform : labPlatformList) {
            if (StringUtils.isNotEmpty(labPlatform.getImageName())) {
                String imagePath = labPlatform.getImageUrl() ;
                try {
                    String imageDataBase64 = readImageAsBase64(imagePath);
                    System.out.println("Image read successfully!");
                    labPlatform.setImageName(imageDataBase64);
                } catch (IOException e) {
                    e.printStackTrace();
                    System.out.println("Failed to read image!");
                }
            }
        }
        return Result.ok(labPlatformList);
    }
}